﻿/**************************************************************
 *
 * 唯一标识：6758e8f5-24b2-494c-8d67-794a2011e3fc
 * 命名空间：Xunit
 * 创建时间：2024/7/12 16:34:45
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Sgr.Data;
using Sgr.Domain.Uow;
using Sgr.Generator;
using Sgr.Generator.Segment;
using Sgr.Threading;
using Sgr.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit.Sgr.Generator;
using Xunit.Sgr.Tests;

namespace Xunit
{
    public class TestFixture : IDisposable
    {
        private readonly IHost _host;

        public TestFixture()
        {
            _host = new HostBuilder().ConfigureAppConfiguration((hostContext, config) =>
            {
                config.AddJsonFile(@"appsettings.json");
            })
            .ConfigureServices((hostContext, serviceCollection) =>
            {
                serviceCollection.AddLogging();
                serviceCollection.AddSgrCore();
                serviceCollection.AddSgrData();
                serviceCollection.AddSgrCaching();
                serviceCollection.AddSgrMysqlDbProvider();
                serviceCollection.AddSgrGenerator();

                // 清理数据库链接配置，改为使用测试数据库
                serviceCollection.RemoveAll<IDataConnectionStringProvider>();
                serviceCollection.TryAddEnumerable(ServiceDescriptor.Singleton<IDataConnectionStringProvider, TestDataConnectionStringProvider>());
            })
            .Build();

            using (var scope = _host.Services.CreateScope())
            {
                var unitOfWorkManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();
                var databaseSeed = scope.ServiceProvider.GetRequiredService<IDatabaseSeed>();
                AsyncHelper.RunSync(async () =>
                {
                    // 这里使用了一个新的 UnitOfWork 来执行 SeedAsync 方法
                    using var uow = unitOfWorkManager.Begin(new UnitOfWorkOption());
                    await databaseSeed.SeedAsync();
                    await uow.CommitAsync();
                });
            }
        }

        public IServiceProvider ServiceProvider => _host.Services;

        public void Dispose()
        {
            _host.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}